package com.haruhinav.Utils;

import com.haruhinav.entity.vo.ImageDetails;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * 文件工具类
 */
@Service
public class FileUtil {

    /**
     * 获取windows原图文件夹路径
     * @return
     */
    public String getWindowsPath(){
        return System.getProperty("user.dir")+Constants.UPLOAD_FILE_RELATIVE_URL;
    }

    /**
     * 获取windows略缩图文件夹路径
     * @return
     */
    public String getWindowsResizePath(){
        return System.getProperty("user.dir")+ Constants.UPLOAD_FILE_RESIZE_RELATIVE_URL;
    }
    /**
     * 获取linux原图文件夹路径
     * @param request www/server/tomcat/webapps/upload
     * @return
     */
    public String getLinuxPath(HttpServletRequest request){
        String path = request.getSession().getServletContext().getRealPath("/");
        String tpath = path.substring(0, path.length()-2);
        return tpath+Constants.UPLOAD_LINUX_FILE_RELATIVE_URL;
    }
    /**
     * 获取linux略缩图文件夹路径
     * @param request www/server/tomcat/webapps/upload/resize
     * @return
     */
    public String getLinuxResizePath(HttpServletRequest request){

        String path = request.getSession().getServletContext().getRealPath("/");
        String tpath = path.substring(0, path.length()-2);
        return tpath+Constants.UPLOAD_LINUX_FILE_RESIZE_RELATIVE_URL;
    }

    /**
     * 压缩原图 生成新的图片 保存到指定路径
     * 返回压缩后图片的名字
     * 不能设置为异步类
     * @param originImage 原图文件
     * @param width 压缩后的宽
     * @param height 压缩后的高
     */
    public String resizeImage(File originImage,HttpServletRequest request,int width,int height){
        String resizeName = "W"+width+"_"+originImage.getName();
        // linux
        String path = getLinuxResizePath(request);
        // windows
//        String path = getWindowsResizePath();
        File file = new File(path);
        if(!file.exists()){
            file.mkdirs();
        }
        try {
            Thumbnails.of(originImage)
                    .size(width, height)
                    .toFile(path+resizeName);
            return resizeName;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 返回图片文件详细信息
     * 在执行这个方法之前要判断是图片文件!!和不能为null
     * @param file
     * @return
     */
    public ImageDetails getImageDetails(MultipartFile file){

        // 获取文件名
        String fileName = file.getOriginalFilename();

        // 获取后缀
        String[] strArray = fileName.split("\\.");
        int suffixIndex = strArray.length -1;
        String fileType =strArray[suffixIndex];//后缀 没有 .
        // 判断后缀
        String imgeArray [] = Constants.WALLPAPER_IMAGE_SUFFIX;
        boolean flag = true;
        for (int i1 = 0; i1 < imgeArray.length; i1++) {
            if(imgeArray[i1].equals(fileType)){
                // 进来表示是图片文件
                flag = false;
                break;
            }
        }
        if(flag){
            return null;
        }

        BufferedImage img = null;
        try {
            ImageDetails details = new ImageDetails();

            // 获取大小 转 MB
            Long size = file.getSize();
            details.setSize((float)size / 1024f / 1024f);
            img = ImageIO.read(file.getInputStream());
            // 获取文件图片文件的md5值
            details.setMd5(DigestUtils.md5DigestAsHex(file.getInputStream()));
            // 获取宽和高
            details.setWidth(img.getWidth());
            details.setHeight(img.getHeight());

            details.setFileName(fileName);
            details.setSuffix(fileType);
            return details;
        } catch (Exception e) {
            // 发生异常 文件非图片
            return null;
        }

    }

    /**
     * 物理删除文件 linux才需要request
     * @param fileName
     * @param resizeName
     * @param request windows不需要
     */
    @Async
    public void deleteFile(String fileName,String resizeName,HttpServletRequest request) {
        // linux
        File file = new File(getLinuxPath(request)+fileName);
        File resizeFile = new File(getLinuxResizePath(request)+resizeName);
        // windows
//        File file = new File(getWindowsPath()+fileName);
//        File resizeFile = new File(getWindowsResizePath()+resizeName);

        if(file.exists() && file.isFile()){
            file.delete();
        }
        if(resizeFile.isFile() && resizeFile.isFile()){
            resizeFile.delete();
        }
    }
}
